from typing import List

from sqlalchemy import select, delete, and_
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.functions.user import get_user
from app.database.models import Unique, User


async def add_unique(session: AsyncSession, telegram_id: int, file_name: str) -> None:

    user = await get_user(session, telegram_id)
    unique = Unique(
        user=user,
        file_name=file_name,
    )
    session.add(unique)

    await session.commit()


async def get_user_creatives(session: AsyncSession, user_id: int) -> List[Unique]:
    q = select(Unique).outerjoin(Unique.user).where(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def delete_user_creatives(session: AsyncSession, user_id: int) -> None:

    user = await get_user(session, user_id, joined=True)

    q = delete(Unique).where(and_(Unique.user == user, Unique.status != "busy"))

    await session.execute(q)

    await session.commit()
